import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import Qt, QRect, QPoint
from PyQt5.QtGui import QPainter, QColor, QRegion, QBrush, QPen


class TransparentWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

        # 设置透明矩形区域（示例值，可根据需要调整）
        self.transparent_rect = QRect(100, 100, 300, 200)

    def initUI(self):
        # 设置窗口属性
        self.setWindowTitle("部分透明窗口")
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 设置窗口大小和位置
        self.setGeometry(100, 100, 800, 600)

        # 添加关闭按钮
        self.close_button = QPushButton("X", self)
        self.close_button.setGeometry(self.width() - 40, 10, 30, 30)
        self.close_button.setStyleSheet("""
            QPushButton {
                background-color: #FF0000;
                color: white;
                font-weight: bold;
                border-radius: 15px;
            }
            QPushButton:hover {
                background-color: #FF5555;
            }
        """)
        self.close_button.clicked.connect(self.close)

    def paintEvent(self, event):
        """重写绘制事件实现部分透明效果"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 1. 绘制半透明背景（除透明矩形外的区域）
        background_color = QColor(30, 30, 30, 180)  # 深灰色半透明
        painter.setBrush(background_color)
        painter.setPen(Qt.NoPen)

        # 创建区域对象：整个窗口减去透明矩形
        region = QRegion(self.rect()) - QRegion(self.transparent_rect)
        painter.setClipRegion(region)
        painter.drawRect(self.rect())

        # 2. 绘制透明矩形边框（可选，用于可视化）
        painter.setClipRegion(QRegion())  # 清除裁剪区域
        border_color = QColor(255, 0, 0, 150)  # 半透明红色
        painter.setPen(QPen(border_color, 2, Qt.DashLine))
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(self.transparent_rect)

        # 3. 在透明矩形内绘制内容（可选）
        painter.setPen(QColor(255, 255, 255))
        painter.drawText(self.transparent_rect, Qt.AlignCenter, "完全透明区域")

    def mousePressEvent(self, event):
        """实现窗口拖动"""
        if event.button() == Qt.LeftButton:
            self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        """窗口拖动实现"""
        if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_position'):
            self.move(event.globalPos() - self.drag_position)
            event.accept()

    def resizeEvent(self, event):
        """窗口大小改变时更新关闭按钮位置"""
        self.close_button.move(self.width() - 40, 10)
        super().resizeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TransparentWindow()
    window.show()
    sys.exit(app.exec_())